package main

import (
	"fmt"

	"github.com/spf13/viper"
	"gopkg.in/ini.v1"
)

func main() {

	// viper 读取json配置文件
	viperLoadJson()

	// viper 读取yml配置文件
	viperLoadYaml()

	// viper 读取ini配置文件
	viperLoadIni()

	// ini 读取ini配置文件
	iniLoadIni()

}

func viperLoadIni() {
	config := viper.New()
	config.AddConfigPath("./conf/")
	config.SetConfigName("b")
	config.SetConfigType("ini")

	if err := config.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			fmt.Println("找不到配置文件..")
		} else {
			fmt.Println("配置文件出错..")
			// Config file was found but another error was produced
		}
	}

	host := config.GetString("redis.host")
	fmt.Println("viper load ini: ", host)
}

func viperLoadYaml() {
	config := viper.New()
	config.AddConfigPath("./conf/")
	config.SetConfigName("a")
	config.SetConfigType("yaml")

	if err := config.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			fmt.Println("找不到配置文件..")
		} else {
			fmt.Println("配置文件出错..")
			// Config file was found but another error was produced
		}
	}

	host := config.GetString("database.host")
	fmt.Println("viper load yml: ", host)

	allSettings := config.AllSettings()
	fmt.Println(allSettings)
}

// viper
// Get(key string) : interface{}
// GetBool(key string) : bool
// GetFloat64(key string) : float64
// GetInt(key string) : int
// GetIntSlice(key string) : []int
// GetString(key string) : string
// GetStringMap(key string) : map[string]interface{}
// GetStringMapString(key string) : map[string]string
// GetStringSlice(key string) : []string
// GetTime(key string) : time.Time
// GetDuration(key string) : time.Duration
// IsSet(key string) : bool
// AllSettings() : map[string]interface{}
func viperLoadJson() {
	config := viper.New()
	config.AddConfigPath("./conf/")
	config.SetConfigName("c")
	config.SetConfigType("json")

	if err := config.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			fmt.Println("找不到配置文件..")
		} else {
			fmt.Println("配置文件出错..")
			// Config file was found but another error was produced
		}
	}

	version := config.GetString("version")
	origin := config.GetString("host.origin")

	fmt.Println(version)
	fmt.Println(origin)

	host := config.GetStringMapString("host")
	fmt.Println(host)
	fmt.Println(host["origin"])
	fmt.Println(host["port"])

	allSettings := config.AllSettings()
	fmt.Println(allSettings)
}

func iniLoadIni() {
	file, err := ini.Load("./conf/b.ini")
	if err != nil {
		fmt.Println("配置文件读取错误，请检查文件路径:", err)
	}

	mysqlUserName := file.Section("mysql").Key("username").String()
	mysqlPassWord := file.Section("mysql").Key("password").String()
	fmt.Println(mysqlUserName)
	fmt.Println(mysqlPassWord)
}
